package priv.dajie.tzzq.mail;

import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.*;
import java.util.Properties;

public class Mail163 {

    private final String HOST = "smtp.163.com";

    private String userName;
    private String password;
    private String toUser;

    {
        // 这里是为避免打包后不能运行的错误
        // javaMail发送MIME类型的邮件需要依赖某些配置文件，比如如果使用MimeMultipart需要找到multipart/mixed的对应配置。这些配置文件将会被类装载器加载，如果不能被正常加载，这些配置文件将无法生效。
        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed; x-java-fallback-entry=true");
        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
        CommandMap.setDefaultCommandMap(mc);
        Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
    }

    public Mail163(String userName, String password, String toUser) {
        this.userName = userName;
        this.password = password;
        this.toUser = toUser;
    }

    public Mail163() {
        File file = new File(System.getProperty("user.dir") + "/config/mail.properties");
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            properties.load(inputStream);
            this.userName = properties.getProperty("username");
            this.password = properties.getProperty("password");
            this.toUser = properties.getProperty("touser");
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(inputStream!=null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void send(String title,String text, String toUserx){
        Properties props = new Properties();
        props.put("mail.smtp.host", HOST);//设置发送邮件的邮件服务器的属性（这里使用网易的smtp服务器）
        props.put("mail.smtp.auth", "true");  //需要经过授权，也就是有户名和密码的校验，这样才能通过验证（一定要有这一条）
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", "994");
        props.put("mail.smtp.port", "994");
        Session session = Session.getDefaultInstance(props);//用props对象构建一个session
//        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);//用session为参数定义消息对象
        System.out.println("准备发送邮件..");
        try {
            message.setFrom(new InternetAddress(userName));// 加载发件人地址
            message.addRecipients(Message.RecipientType.TO, toUserx);
            message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(userName));//设置在发送给收信人之前给自己（发送方）抄送一份，不然会被当成垃圾邮件，报554错
            message.setSubject(title);//加载标题
            Multipart multipart = new MimeMultipart();//向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            BodyPart contentPart = new MimeBodyPart();//设置邮件的文本内容
            contentPart.setText(text);
            multipart.addBodyPart(contentPart);
            message.setContent(multipart);//将multipart对象放到message中
            message.saveChanges(); //保存邮件
            Transport transport = session.getTransport("smtp");//发送邮件
            transport.connect(HOST, userName, password);//连接服务器的邮箱
            transport.sendMessage(message, message.getAllRecipients());//把邮件发送出去
            transport.close();//关闭连接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(String title, String text){
        send(title, text, toUser);
    }

}
